<template>
  <el-card>
    <h1 class="mb-4">{{ $t("充值信息") }}</h1>
    <el-form
      :model="form"
      ref="formRef"
      label-width="240px"
      :rules="rechargeRules"
    >
      <el-form-item :label="$t('充值金额')" prop="amount">
        <el-input
          v-model="form.amount"
          type="number"
          :placeholder="$t('请输入充值金额')"
          style="width: 50%"
        ></el-input>
      </el-form-item>
      <el-form-item :label="$t('充值币种')" prop="currency">
        <el-select
          :popper-append-to-body="false"
          popper-class="optionsContent"
          v-model="form.currency"
          :placeholder="$t('请选择币种')"
          @change="handleCurrencyChange"
          style="width: 50%"
        >
          <el-option
            v-for="item in currencyList"
            :key="item.id"
            :label="item.name"
            :value="item.name"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <h1 class="mb-4">{{ $t("支付信息") }}</h1>
      <el-form-item :label="$t('KVB账户')">
        <span>{{ cardInfo.bank_card_no || "--" }}</span>
      </el-form-item>
      <el-form-item :label="$t('账户可用余额')">
        <span>{{ cardInfo.symbol }} {{ cardInfo.total_available }} </span>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :icon="SuccessFilled"
          size="large"
          class="w-48 mt-5"
          @click="showConfirmDialog"
          >{{ $t("确认提交") }}</el-button
        >
      </el-form-item>
    </el-form>
  </el-card>
  <el-dialog v-model="dialogVisible" :title="$t('安全验证')" width="30%">
    <el-form :model="state.verticalForm" :rules="rules">
      <el-form-item prop="trade_password">
        <el-input
          v-model="state.verticalForm.trade_password"
          :placeholder="$t('VA-请输入支付密码')"
          clearable
          type="password"
          show-password
        />
      </el-form-item>
      <el-form-item prop="email_code">
        <div class="flex items-center justify-between flex-1">
          <el-input
            v-model="state.verticalForm.email_code"
            :placeholder="$t('请输入邮箱验证码')"
            size="large"
          >
          </el-input>

          <el-button
            size="large"
            plain
            type="primary"
            class="w-40 ml-4"
            @click="handleCaptcha"
            v-if="!codesms.disabled"
          >
            {{ $t("获取验证码") }}
          </el-button>
          <el-button
            size="large"
            type="primary"
            class="w-40 ml-4"
            v-else
            disabled
          >
            {{ codesms.count }}{{ $t("秒后重新获取") }}
          </el-button>
        </div>
      </el-form-item>
      <el-form-item prop="google_code" v-if="isVAlid">
        <el-input
          v-model="state.verticalForm.google_code"
          :placeholder="$t('请输入谷歌验证码')"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <div class="flex items-center justify-center w-full">
          <el-button
            type="primary"
            @click="confirm"
            class="w-40"
            v-loading="loading"
            >{{ $t("确认") }}</el-button
          >
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script setup>
import { ref, reactive, computed } from "vue";
import { SuccessFilled } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { GetVaBalance, VARecharge } from "@/api/VAAccount";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import { useMerchantStore } from "@/store/modules/merchant";
const useMerchant = useMerchantStore();
import { useUserStore } from "@/store/modules/user";
import { emailSendApi } from "@/api/login/index";
import { useRouter } from "vue-router";
const router = useRouter();

const useUser = useUserStore();
const formRef = ref();

const isVAlid = ref(false);

const state = reactive({
  verticalForm: {
    trade_password: "",
    email_code: "",
    google_code: "",
  },
});

const codesms = reactive({
  disabled: false,
  total: 60,
  count: 0,
});

// 校验
const rules = computed(() => {
  return {
    trade_password: [
      { required: true, message: t("请输入支付密码"), trigger: "blur" },
    ],
    email_code: [
      { required: true, message: t("请输入邮箱验证码"), trigger: "blur" },
    ],
    google_code: [
      { required: true, message: t("请输入谷歌验证码"), trigger: "blur" },
    ],
  };
});

// 倒计时
const timerHandle = () => {
  codesms.count = codesms.total;
  codesms.disabled = true;

  let timer = setInterval(() => {
    if (codesms.count > 1 && codesms.count <= codesms.total) {
      codesms.count--;
    } else {
      codesms.disabled = false;
      clearInterval(timer);
    }
  }, 1000);
};

//发送验证码
const handleCaptcha = async () => {
  try {
    timerHandle();
    const res = await emailSendApi({
      email: useUser.userInfo.userName,
      code_type: "va_recharge",
    });
    ElMessage({
      type: "success",
      message: t("发送验证码成功"),
    });
    // console.log(res);
  } catch (error) {}
};

const form = ref({
  amount: "",
  currency: "",
});

const checkAmount = (rule, value, callback) => {
  const { total_available } = cardInfo.value;
  if (!value) {
    return callback(new Error(t("请输入充值金额")));
  }
  if (Number(value) > Number(total_available)) {
    return callback(new Error(`${t("充值金额不能大于")}${total_available}`));
  }
  callback();
};

const rechargeRules = ref({
  amount: [
    {
      required: true,
      message: t("请输入充值金额"),
      trigger: "blur",
    },
    {
      validator: checkAmount,
      trigger: "blur",
    },
  ],
  currency: [
    {
      required: true,
      message: t("请选择币种"),
      trigger: "change",
    },
  ],
});
const currencyList = ref([]);
const cardInfo = ref({});

const handleCurrencyChange = (value) => {
  getCurrencyAmount();
};

const getCurrencyAmount = () => {
  currencyList.value.forEach((item) => {
    if (item.name === form.value.currency) {
      cardInfo.value.total_available = item.amount;
      cardInfo.value.symbol = item.symbol;
    }
  });
  return cardInfo.value;
};

// 获取资产余额
const getCurrencyData = async () => {
  try {
    const data = await GetVaBalance();
    currencyList.value = data.currency;
    form.value.currency = data.currency[0].name;
    cardInfo.value.bank_card_no = data.bank_card_no || "--";
    getCurrencyAmount();
  } catch {}
};

const dialogVisible = ref(false);

const showConfirmDialog = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      dialogVisible.value = true;
    } else {
      console.log("error submit!", fields);
    }
  });
};

const handleClick = (order_no) => {
  router.push({
    path: "/account/recharge/KVBDetails",
    query: {
      order_no,
    },
  });
};

const loading = ref(false);

const confirm = () => {
  const params = {
    amount: form.value.amount,
    currency: form.value.currency,
    trade_password: state.verticalForm.trade_password,
    email_code: state.verticalForm.email_code,
  };
  if (isVAlid.value) {
    params.google_code = state.verticalForm.google_code;
  }
  loading.value = true;
  VARecharge(params)
    .then((res) => {
      if (res) {
        dialogVisible.value = false;
        loading.value = false;
        ElMessage.success(t("提交成功"));
        handleClick(res.order_no);
      }
      loading.value = false;
      codesms.disabled = false;
      state.verticalForm = {};
    })
    .catch(() => {
      loading.value = false;
      codesms.disabled = false;
      state.verticalForm = {};
    });
};

getCurrencyData();
//   判断是否有谷歌验证
if (useMerchant.merchantInfo.va > 0) {
  isVAlid.value = true;
} else {
  isVAlid.value = false;
}
</script>
